package bll

import (
	"context"
	"encoding/hex"
	"signal/utils"

	"gitlab.local/backend/proto/dto"
	log "signal/collector/logger"
	"signal/lib/trace_log"
	"signal/model"
)

var Setting = &setting{}

// 服务端向设备设置
type setting struct{}

func (s *setting) init() func() {
	return func() {}
}

func (s *setting) Setting(ctx context.Context, in *dto.SettingRequest) error {
	var err error
	defer func() {
		trace_log.DebugLogger(in.Sn, "Setting 执行 data:", utils.ToJsonString(in), " err:", err)
	}()

	if in.PlayVoice != nil {
		err = s.playVoice(in)
	}
	if in.AutoLockTime != nil {
		err = s.setAutoLockTime(in)
	}
	return err
}

func (s *setting) setAutoLockTime(in *dto.SettingRequest) error {
	var (
		err        error
		id         uint8
		requestKey string
		sn         = in.Sn
	)

	defer func() {
		trace_log.DebugLogger(in.Sn, "setAutoLockTime 执行 data:", utils.ToJsonString(in), " err:", err)
	}()

	if requestKey, id, err = Session.GetRequestID(in.Sn, model.CmdSmartConfig); err != nil {
		log.Error("get request error ", err)
		return err
	}

	config := &model.SmartConfig{
		TimedPowerOffEnable: true,
		TimedPowerOff:       uint8(*in.AutoLockTime),
	}

	pkt := model.BuildPacket(model.CmdSmartConfig, id, config.ToHexBytes())
	log.Infof("send set auto lock time command to device: %X", pkt.ToHexBytes())

	if _, err = Session.SyncRequest(sn, requestKey, pkt); err != nil {
		log.Errorf("send signal to device error:  %s", err)
		_ = Session.ReleaseID(sn, id)
		return err
	}

	return nil
}

func (s *setting) playVoice(in *dto.SettingRequest) error {
	var (
		err        error
		id         uint8
		requestKey string
		sn         = in.Sn
	)

	defer func() {
		trace_log.DebugLogger(in.Sn, "playVoice 执行 data:", utils.ToJsonString(in), " err:", err)
	}()

	if requestKey, id, err = Session.GetRequestID(in.Sn, model.CmdPlayVoice); err != nil {
		log.Error("get request error ", err)
		return err
	}

	// 播放语音
	data := model.PlayerVoice{
		Id:    uint8(*in.PlayVoice),
		Count: 8,
		Time:  2,
	}

	if *in.PlayVoice < 0 {
		data.Count = 0
		data.Time = 0
	}

	pkt := model.BuildPacket(model.CmdPlayVoice, id, data.ToHexBytes())
	trace_log.DebugLogger(in.Sn, "playVoice 执行 data:", utils.ToJsonString(in), " body:", hex.EncodeToString(data.ToHexBytes()))
	log.Infof("send play voice command to device: %X", pkt.ToHexBytes())

	if _, err = Session.SyncRequest(sn, requestKey, pkt); err != nil {
		log.Errorf("send signal to device error:  %s", err)
		_ = Session.ReleaseID(sn, id)
		return err
	}

	return nil
}
